import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:aichat_flutter_wallet/module/module_integral/pages/check_calendar.dart';
import 'package:aichat_flutter_wallet/module/module_integral/pages/points_list.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/easyloading.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_language/lib_language.dart';
import 'package:lib_util/utils/utils.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:widgets_to_image/widgets_to_image.dart';

import '../../../app_config.dart';
import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/router/Routers.dart';
import '../../../module_common/utils/env.utils.dart';
import '../../../module_common/utils/task_code_to_flutter.dart';
import '../../../module_common/widgets/button/public_button.dart';
import '../../../module_common/widgets/header/page_integral_header.dart';
import '../../../module_common/widgets/image/public_image.dart';
import '../../../module_common/widgets/page_status_com.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import 'package:animated_flip_counter/animated_flip_counter.dart';
import '../model/integral_api.dart';
import '../model/integral_model.dart';
import '../widgets/beginner_tasks_page.dart';
import '../widgets/checkin_tip.dart';
import '../widgets/claim_successful.dart';
import '../widgets/sliver_integral_delegate.dart';
import 'integral_detail.dart';
import 'package:url_launcher/url_launcher.dart';
class IntegralPage extends StatefulWidget {
  IntegralPage({
    super.key,
  });

  @override
  State<IntegralPage> createState() => IntegralPageState();
}

class IntegralPageState extends State<IntegralPage> with TickerProviderStateMixin {
  ScrollController? _scrollController;
  ScrollController? _scrollController2;
  TabController? _tabController;
  StreamSubscription? walletSubscription;
  int _currentIndex = 0;
  // 是否完成新手状态
  int isFinish = 0;
  bool isSaving = false;
  int totalScore = 0;
  int totalDays = 0;
  bool claimStatus = false;
  List<String> recordList= [];
  String currentDate= '';
  // 客服 id
  String? custom_uid;

  // WidgetsToImageController to access widget
  WidgetsToImageController controller = WidgetsToImageController();

  // 头部选项 tabs
  List<IntegralTabsItemType> tabs = [
    IntegralTabsItemType(name: 'Beginner Tasks', value: TaskType.NoviceTasks, isLoading: false, data: []),
    IntegralTabsItemType(name: 'Daily Tasks', value: TaskType.DailyTasks, isLoading: false, data: []),
    IntegralTabsItemType(name: 'Advanced Tasks', value: TaskType.AdvancedTasks, isLoading: false, data: []),
  ];

  // 内容 展示列表

  // 签到 显示 列表
  List<SignInItemType> SignInfoLists = [
    SignInItemType(amount: 1, isSignIn: false, isNormal: true),
    SignInItemType(amount: 1, isSignIn: false, isNormal: true),
    SignInItemType(amount: 1, isSignIn: false, isNormal: true),
    SignInItemType(amount: 1, isSignIn: false, isNormal: true),
    SignInItemType(amount: 1, isSignIn: false, isNormal: true),
    SignInItemType(amount: 1, isSignIn: false, isNormal: true),
    SignInItemType(amount: 12, isSignIn: false, isNormal: false),
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController = ScrollController();
    _scrollController2 = ScrollController();
    _tabController = TabController(length: tabs.length, vsync: this);
    _tabController?.addListener(_handleTabSelection);
    initPage();
  }

  @override
  void dispose() {
    /// 取消路由订阅
    super.dispose();
    _scrollController?.dispose();
    _scrollController2?.dispose();
    _tabController?.dispose();
    walletSubscription?.cancel();
  }

  initSPData(String uId) {
    _currentIndex = SP().getTaskIndex()?? _currentIndex;
    final cacheSignInfoData = SP().getIntegralSignInData(uId);
    if(cacheSignInfoData.isNotEmpty){
      final cacheDate= cacheSignInfoData[0].date;
      if(cacheDate.isNotEmpty){
        // 等于 昨天 或者 今天都取
        if(cacheDate == currentDate ){
          SignInfoLists = cacheSignInfoData;
        }
      }
    }
    for(var i=0;i<tabs.length;i++){
      final tab = SP().getTaskSignInData(uId+'_'+i.toString());
      if(tab.isNotEmpty){
        tabs[i].data = tab;
      }
    }
    if (mounted) setState(() {});
    return true;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    var config = AppConfig.of(context);
    if (config?.flavorName == 'development') {
      initPage();
    }
    /// 路由订阅
  }

  void _handleTabSelection() {
    try {
      final index = _tabController!.index;
      if (tabs[index].isLoading) {
        return;
      }
      _currentIndex = index;
      tabs[index].isLoading = true;
      if (mounted) setState(() {});
      IntegralApi.getTaskList(tabs[index].value).then((TaskListInterface resp) async {
        final taskList = resp.task_list;
        custom_uid = resp.custom_uid!;
        if([1,2].contains(index)){
          // 刷新 页面 未完成状态
          IntegralApi.getTaskIsFinishStatus(TaskType.NoviceTasks).then((status) {
            isFinish = status==null? isFinish : int.parse(status);
            if (mounted) setState(() {});
          });
        }
        if(index == 1){
          List<Future<IntegralTabsItemDataType>> result = [];
          for (var item in taskList) {
            if (item.status == 1) {
              if([301,302].contains(item.task_code)){
                result.add(Future(() async {
                  final String? response= await IntegralApi.getScoreMsgCount(item.task_code.toString());
                  return IntegralTabsItemDataType(
                      title: item.task_name + (response??''),
                      icon: item.icon,
                      task_id: item.id,
                      task_code: item.task_code,
                      describe: item.intro,
                      score: int.parse(item.integral),
                      status: item.task_status);
                }));
                continue;
              }
              if([303,308].contains(item.task_code)){
                result.add(Future(() async {
                  final response= await IntegralApi.taskProgress(code: item.task_code);
                  return IntegralTabsItemDataType(
                      title: item.task_name ,
                      icon: item.icon,
                      task_id: item.id,
                      task_code: item.task_code,
                      describe: response != null?jsonEncode(response['task_rules']):'[]',
                      score: int.parse(item.integral),
                      status: item.task_status);
                }));
                continue;
              }
              result.add(Future.value(IntegralTabsItemDataType(
                  title: item.task_name,
                  icon: item.icon,
                  task_id: item.id,
                  task_code: item.task_code,
                  describe: item.intro,
                  score: int.parse(item.integral),
                  status: item.task_status)));
            }
          }
          Future.wait(result).then((value)  async {
              tabs[index].data = value;
              tabs[index].isLoading = false;
              if(result.isNotEmpty){
                final userId = NativeChannelBridge.instance.appCommMsg?.userId;
                await SP().setTaskIndex(index,userId!);
                await SP().setTaskSignInData(value,userId+'_'+ index.toString());
              }
              if (mounted) setState(() {});
          });
          return;
        }
        List<IntegralTabsItemDataType> result = [];

        for (var item in taskList) {
          if (item.status == 1) {
            result.add(IntegralTabsItemDataType(
                title: item.task_name,
                icon: item.icon,
                task_id: item.id,
                task_code: item.task_code,
                describe: item.intro,
                score: int.parse(item.integral),
                status: item.task_status));
          }
        }
        tabs[index].data = result;
        tabs[index].isLoading = false;
        if(result.isNotEmpty){
          final userId = NativeChannelBridge.instance.appCommMsg?.userId;
          await SP().setTaskIndex(index,userId!);
          await SP().setTaskSignInData(result,userId+'_'+ index.toString());
        }
        if (mounted) setState(() {});
      });
    } catch (e) {
      kaiPrint('切换tab 数据异常 $e');
    }
  }

  initPage() async {
    final userId = NativeChannelBridge.instance.appCommMsg?.userId;
    if (userId != '0' && userId != null && userId.isNotEmpty) {
      DateTime now = DateTime.now();
      DateFormat dateFormat = DateFormat('yyyy-MM-dd');
      currentDate =  dateFormat.format(now);
      // 先显示 缓存数据
      await initSPData(userId);
      // 初始化显示 总积分
      IntegralApi.getUnclaimedScore().then((score) {
        totalScore = score == -1 ? totalScore : score;
        if (mounted) setState(() {});
      });
      // 获取 签到信息 列表
      IntegralApi.getTaskList(TaskType.SignIn).then((TaskListInterface resp) {
        final taskList= resp.task_list;
        handleSignInfo(taskList);
      });
      // 获取 新手任务
      IntegralApi.getTaskIsFinishStatus(TaskType.NoviceTasks).then((index) {
        _currentIndex = index==null? 0 : int.parse(index);
        isFinish = index==null? 0 : int.parse(index);
        kaiPrint('_currentIndex  $_currentIndex');
        _tabController!.animateTo(_currentIndex);
        _handleTabSelection();
        if (mounted) setState(() {});
      });
    }
  }

  // 处理 签到数据 操作数据 ---------------------------------
  handleSignInfo(List<TaskInfoType> taskRules) {
    try {
      // 提取规则 以及积分
      List<SignRuleType> dailyRules = [];
      List<SignRuleType> specialRules = [];
      for (var element in taskRules) {
        dynamic groups = element.integral_rules;
        if (element.integral_rules.runtimeType == String) {
          groups = jsonDecode(element.integral_rules);
        }
        final regex = RegExp(r'\d+');
        for (var item in groups) {
          final match = regex.firstMatch(item['value']);
          if (match != null) {
            specialRules.add(SignRuleType(day: int.parse(match.group(0)!), integral: item['integral']));
          } else {
            dailyRules.add(SignRuleType(day: 1, integral: item['integral']));
          }
        }
      }
      kaiPrint('日常规则 ${dailyRules} ${dailyRules.length}');
      kaiPrint('特殊规则 ${specialRules} ${specialRules.length}');
      // 获取 用户签到信息
      IntegralApi.getSignDate(historyDate: null).then((signDateList) async {
        kaiPrint('getSignDate $signDateList');
        recordList = [];
        // 网络 异常 不处理
        if (signDateList == null) {
          return;
        }
        List<SignInItemType> signInfo = [];
        // 签到 数据 空数据 情况下  ： 断签  或者 初签到
        if (signDateList.isEmpty) {
          // 保证 7天
          for (var i = 1; i <= 7; i++) {
            final signGroup = specialRules.firstWhereOrNull((ruleItem) {
              return ruleItem.day == i;
            });
            if (signGroup == null) {
              if (dailyRules.isEmpty) {
                break;
              }
              signInfo.add(SignInItemType(amount: dailyRules.first.integral, isSignIn: false, isNormal: true,date: currentDate));
            } else {
              signInfo.add(SignInItemType(amount: signGroup.integral, isSignIn: false, isNormal: false,date: currentDate));
            }
          }
        } else {
          final record =  signDateList[signDateList.length-1];
          // 判断当前 按钮是否 要禁用调
          int days = currentDate ==record.start? 1 : DateTime.parse(currentDate).difference(DateTime.parse(record.start)).inDays ;
          bool isKeepOn = record.day == days || (days + 1 == record.day) || (days - 1 == record.day);
          if(isKeepOn){
            for(var i = 0;i<record.day;i++){
              final nextDay = DateTime.parse(record.start).add(Duration(days: i));
              final element = DateFormat('yyyy-MM-dd').format(nextDay).toString();
              recordList.add(element);
            }
          }
          kaiPrint('recordList $recordList');
          kaiPrint('days $days');
          kaiPrint('isKeepOn $isKeepOn');
          // 现在 签到的总天数
          totalDays = isKeepOn? record.day : 0;
          kaiPrint('totalDays  $totalDays');
          int mostRecentNum =  totalDays % 7 ;
          for (var i = 1; i <= 7; i++) {
            // 最近的签到日期
            final signGroup = specialRules.firstWhereOrNull((ruleItem) {
              return ruleItem.day == ((totalDays - mostRecentNum) + i);
            });
            if (signGroup == null) {
              signInfo
                  .add(SignInItemType(amount: dailyRules.first.integral, isSignIn: isKeepOn? mostRecentNum >= i : false, isNormal: true,date: currentDate));
            } else {
              signInfo.add(SignInItemType(amount: signGroup.integral, isSignIn:  isKeepOn? mostRecentNum >= i : false, isNormal: false,date: currentDate));
            }
          }
        }
        if (signInfo.isEmpty) {
          return;
        }
        SignInfoLists = signInfo;
        final userId = NativeChannelBridge.instance.appCommMsg?.userId;
        await SP().setIntegralSignInData(signInfo, userId!);
        if (mounted) setState(() {});
      });
    } catch (e) {
      kaiPrint('$e');
    }
  }

  // 告诉我 某个 日期 是否为 这周内的
  bool handleMostRecentDate(String dateString) {
    final targetDate = DateTime.parse(dateString); // 指定要检查的日期
    final now = DateTime.now();
    final monday = now.subtract(Duration(days: now.weekday - 1));
    final sunday = monday.add(Duration(days: 6));

    if (targetDate.isAfter(monday) && targetDate.isBefore(sunday)) {
      // final dayOfWeek = targetDate.weekday;
      return true;
    }
    return false;
  }

  bool btnStatus = false;

  // 点击签到
  _taskSignIn() async {
    if (btnStatus) {
      return;
    }
    try {
      btnStatus = true;
      IntegralApi.postUserSignIn().then((status) {
        //-1签到失败 -2新手任务未完成 0已签到 1签到成功
        if (status == -2) {
          CheckInTipDialog.showAboutGas(context);
        }
        if (status == -1) {
          Toast.show(context, message: "Sign-in failed", status: '-1', position: Dpositon.top);
        }
        if (status == 0) {
          Toast.show(context, message: "Sign-in completed", status: '-1', position: Dpositon.top);
        }
        if (status == 1) {
          // 签到 成功 更新 当前 积分
          IntegralApi.getUnclaimedScore().then((score) {
            totalScore = score == -1 ? totalScore : score;
            totalDays = totalDays + 1;
            if (SignInfoLists.isNotEmpty) {
              SignInfoLists[totalDays - 1].isSignIn = true;
              Toast.show(context, message: "Sign-in Successfully", status: '1', position: Dpositon.top);
            }
            if(!recordList.contains(currentDate)){
              recordList.add(currentDate);
            }
            if (mounted) setState(() {});
          });
          // 有问题
        }
        btnStatus = false;
        setState(() {});
      });
    } catch (e) {
      btnStatus = false;
    }
  }

  // 获取 签到任务 接口

  Widget SignInItem(SignInItemType item, int index, {bool isShowMargin = false}) {
    return Container(
      width: 38.w,
      height: 76.w,
      margin: EdgeInsets.only(right: !isShowMargin ? 0 : 6.5.w),
      alignment: Alignment.center,
      child: Column(
        children: [
          Container(
            width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.w),
              color: !item.isNormal ? Color.fromRGBO(255, 242, 210, 1) : Color.fromRGBO(246, 246, 246, 1),
            ),
            child: Column(
              children: [
                SizedBox(
                  height: 6.w,
                ),
                Text(
                  '+${item.amount}',
                  style: TextStyle(
                      color: item.isNormal ? Color.fromRGBO(51, 51, 51, 1) : Color.fromRGBO(149, 86, 43, 1),
                      fontWeight: FontWeight.w500,
                      fontSize: 12.w),
                ),
                Visibility(
                    visible: item.isSignIn,
                    child: PublicImage(
                      image: 'assets/images/integral/get_money.png',
                      width: 20.w,
                      height: 20.w,
                    )),
                Visibility(
                    visible: !item.isSignIn,
                    child: Column(
                      children: [
                        Visibility(
                            visible: item.isNormal,
                            child: PublicImage(
                              image: 'assets/images/integral/money.png',
                              width: 20.w,
                              height: 20.w,
                            )),
                        Visibility(
                            visible: !item.isNormal,
                            child: PublicImage(
                              image: 'assets/images/integral/more_money.png',
                              width: 20.w,
                              height: 20.w,
                            ))
                      ],
                    )),
                SizedBox(
                  height: 6.w,
                ),
              ],
            ),
          ),
          SizedBox(
            height: 3.w,
          ),
          Text(
            'Day ${index + 1}',
            style: TextStyle(
                color: item.isSignIn ? Color.fromRGBO(190, 189, 202, 1) : Color.fromRGBO(51, 51, 51, 1),
                fontSize: 12.w,
                fontWeight: FontWeight.w400),
          )
        ],
      ),
    );
  }

  Widget PointsSignInCardWidget() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.transparent,
        boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(224, 216, 255, 1),
            spreadRadius: 2.w,
            blurRadius: 10.w,
            offset: Offset(0, 1.w),
          ),
        ],
      ),
      margin: EdgeInsets.only(left: 20.w, right: 20.w),
      child: Stack(
        children: [
          Positioned(
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              child: PublicImage(
                image: 'assets/images/integral/integral_card.png',
                width: double.infinity,
                height: 203.w,
              )),
          Column(
            children: [
              SizedBox(
                height: 10.w,
              ),
              Container(
                margin: EdgeInsets.only(left: 15.w, right: 15.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    RichText(
                      softWrap: false,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      text: TextSpan(
                        text: totalDays.toString(),
                        style: TextStyle(
                            color: Color.fromRGBO(134, 103, 254, 1), fontSize: 14.sp, fontWeight: FontWeight.w500),
                        children: [
                          TextSpan(
                            text: ' Days streak',
                            style: TextStyle(
                                color: Color.fromRGBO(51, 51, 51, 1), fontSize: 14.sp, fontWeight: FontWeight.w500),
                          ),
                        ],
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (_) {
                              return CheckCalendarPage();
                            },
                            settings: RouteSettings(name: Routes.checkCalendarPage)));
                      },
                      child: Row(
                        children: [
                          PublicImage(
                            image: 'assets/images/integral/calendar.png',
                            width: 16.w,
                            height: 16.w,
                          ),
                          SizedBox(
                            width: 5.w,
                          ),
                          Text(
                            'Check calendar',
                            style: TextStyle(
                                color: Color.fromRGBO(83, 69, 137, 1), fontSize: 12.sp, fontWeight: FontWeight.w400),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 20.w,
              ),
              Container(
                width: double.infinity,
                height: (50 + 5 + 19).w,
                margin: EdgeInsets.only(left: 15.w, right: 0.w),
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: SignInfoLists.length, // 列表项的数量
                  itemBuilder: (BuildContext context, int index) {
                    return SignInItem(SignInfoLists[index], index, isShowMargin: index != (SignInfoLists.length - 1));
                  },
                ),
              ),
              SizedBox(
                height: 19.w,
              ),
              PublicButton(
                  margin: EdgeInsets.only(left: 20.w, right: 20.w),
                  radius: 10.w,
                  height: 46.w,
                  type: ButtonType.private,
                  disabledStatus: recordList.contains(currentDate),
                  text: recordList.contains(currentDate)? 'Checked':'Check-in',
                  onClick: () {
                    if(recordList.contains(currentDate)){
                      return;
                    }
                    _taskSignIn();
                  }),
            ],
          )
        ],
      ),
      height: 200.w,
    );
  }

  List<Widget> getTabs() {
    return tabs
        .map((e) => Container(
              height: 42.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(0.w), // 设置圆角半径为 10.0
              ),
              // padding: EdgeInsets.only(left: 8.w, right: 8.w),
              child: Text(
                e.name,
                overflow: TextOverflow.visible,
                softWrap: false,
                style: TextStyle(fontSize: 14.w, fontWeight: FontWeight.w500),
              ),
            ))
        .toList(growable: false);
  }

  Widget integralHeader() {
    return Container(
        child: Stack(children: [
      Positioned(
          top: -79.w,
          left: 0,
          right: 0,
          child: PublicImage(
            image: 'assets/images/integral/integral_bg.png',
            width: double.infinity,
            height: 285.5.w,
          )),
      Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // SizedBox(
            //   height: 27.w,
            // ),
            Padding(
              padding: EdgeInsets.fromLTRB(18.w, 19.w, 0, 5.w),
              child: Text(
                'My KC',
                style: TextStyle(
                  fontSize: 12.sp,
                  height: 0.9,
                  fontWeight: FontWeight.w500,
                  color: Color.fromRGBO(106, 106, 106, 1),
                ),
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (_) {
                      return IntegralDetailPage();
                    },
                    settings: RouteSettings(name: Routes.integralDetailPage)));
              },
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SizedBox(
                    width: 20.w,
                  ),
                  AnimatedFlipCounter(
                    value: totalScore,
                    fractionDigits: 0, // decimal precision
                    textStyle: TextStyle(
                      fontSize: 42.sp,
                      height: 0.9,
                      fontWeight: FontWeight.w700,
                      fontFamily: '_DIN',
                      color: Color.fromRGBO(51, 51, 51, 1),
                    ),
                  ),
                  SizedBox(
                    width: 5.w,
                  ),
                  PublicImage(
                    image: 'assets/images/integral/arrow_right.png',
                    width: 12.w,
                    height: 12.w,
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 15.w,
            ),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                if (claimStatus) {
                  return;
                }
                claimStatus = true;
                try {
                  EasyLoading.generateLoadingFuture(
                          IntegralApi.postMultiClaimIntegral(taskType: tabs[_currentIndex].value))
                      .then((value) {
                        if(value == false){
                          claimStatus = false;
                          return Toast.show(context, message: 'No points to collect yet',status: '-1');
                        }
                    claimStatus = false;
                    _handleTabSelection();
                    // 更新 总 任务积分
                    IntegralApi.getUnclaimedScore().then((score) {
                      totalScore = score == -1 ? totalScore : score;
                      if (mounted) setState(() {});
                    });
                  });
                } catch (e) {
                  kaiPrint('e $e');
                  claimStatus = false;
                }
              },
              child: Container(
                width: 123.w,
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Color.fromRGBO(192, 248, 247, 1),
                      Color.fromRGBO(213, 194, 255, 1),
                      Color.fromRGBO(255, 251, 238, 1),
                    ], // 设置渐变的颜色列表
                    begin: FractionalOffset.bottomLeft, // 设置渐变的起始位置FractionalOffset.bottomRight
                    end: FractionalOffset.topRight, // 设置渐变的结束位置FractionalOffset.bottomRight
                  ),
                  borderRadius: BorderRadius.circular(10.w),
                  border: Border.all(
                    color: Colors.white,
                    width: 1.w,
                  ),
                ),
                margin: EdgeInsets.only(left: 20.w),
                padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 6.w, bottom: 6.w),
                child: Row(
                  children: [
                    PublicImage(
                      image: 'assets/images/integral/more_money.png',
                      width: 28.w,
                      height: 23.w,
                    ),
                    SizedBox(
                      width: 6.w,
                    ),
                    Text(
                      'Claim Now',
                      style: TextStyle(
                        fontSize: 12.sp,
                        height: 0.9,
                        fontWeight: FontWeight.w500,
                        color: Color.fromRGBO(51, 51, 51, 1),
                      ),
                    )
                  ],
                ),
              ),
            ),
            SizedBox(
              height: 17.w,
            ),
            PointsSignInCardWidget()
          ],
        ),
        height: 360.w,
      ),
          Positioned(
              top: 19.w,
              right: 0,
              child: InkWell(
                highlightColor: Colors.transparent,
                splashColor:  Colors.transparent,
                onTap: () async{
                  final Uri _url = Uri.parse(EnvUtil.getEnvConfig().integralRuleUri+'/pages/integral-rule');
                  if (!await launchUrl(_url)) {
                    throw Exception('Could not launch $_url');
                  }
                },
                child: Container(
                  height: 30.w,
                  width: 54.w,
                  alignment: Alignment.center,
                  decoration:  BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(topLeft:  Radius.circular(54.w),bottomLeft: Radius.circular(54.w)),
                  ),
                  child: Text('Rules',style: TextStyle(
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                      color: Color.fromRGBO(51, 51, 51, 1)
                  ),),
                ),
              ) ),
    ]));
  }

  // -----------------------  开启任务-------------------
  // Widget BeginnerTasksPageList(){
  //
  // }

  Widget PosterWidget() {
    final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
    return WidgetsToImage(
        controller: controller,
        child: Container(
          child: Stack(
            children: [
              PublicImage(
                image: 'assets/images/integral/poster.png',
                width: 310.w,
                // height: 376.w,
                height: 416.w,
              ),
              Positioned(
                  right: 5.5.w,
                  bottom: 3.w,
                  child: QrImageView(
                    data: '${EnvUtil.getEnvConfig().downLoadUri}/pages/always-downloads?userId=${userId}',
                    version: QrVersions.auto,
                    size: 70.w,
                  )),
            ],
          ),
        ));
  }

  Widget shareWidget(int code) {
    return Container(
      width: double.infinity,
      height: 576.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(15.w), topRight: Radius.circular(15.w)),
        // 设置圆角半径
        color: Colors.white, // 设置背景颜色
      ),
      child: Column(
        children: [
          Stack(
            children: [
              Positioned(
                  left: 0,
                  top: 0,
                  child: InkWell(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      padding: EdgeInsets.only(top: 15.w, bottom: 15.w, left: 20.w, right: 20.w),
                      child: PublicImage(
                        image: 'assets/images/common/dialog-close.png',
                        width: 20.w,
                        height: 20.w,
                      ),
                    ),
                  )),
              Container(
                  alignment: Alignment.center,
                  height: 50.w,
                  child: Text(
                    'Share poster',
                    style: TextStyle(
                        height: 1.5, fontSize: 16.w, fontWeight: FontWeight.w500, color: Color.fromRGBO(51, 51, 51, 1)),
                  ))
            ],
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(10.w),
            child: PosterWidget(),
          ),
          SizedBox(
            height: 20.w,
          ),
          PublicButton(
            onClick: () {
              _generatePosterImage(code);
            },
            text: 'Share',
            image: PublicImage(
              width: 16.w,
              height: 16.w,
              image: 'assets/images/integral/btn_share.png',
            ),
            type: ButtonType.private,
          )
        ],
      ),
    );
  }

  Future<bool?> _generatePosterImage(int code) async {
    try {
      if (isSaving == true) {
        return null;
      }
      isSaving = true;
      EasyLoading.generateLoadingFuture(controller.capture()).then((value) async {
        Uint8List? bytes = value ;
        IntegralApi.getUserTaskUpdate(
            taskType: code == 309 ? TaskType.DailyTasks : TaskType.NoviceTasks, taskCode: code);
        NativeChannelBridge().sharePoster(bytes);
        bool isLast = !Navigator.canPop(context);
        if (!isLast) {
          Navigator.pop(context);
        }
        isSaving = false;

      });
      return null;
    } catch (e) {
      kaiPrint("error $e");
      isSaving = false;
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: PageIntegralCom(
          title: 'Task Center',
          // 分享
          goShare: () {
            EasyLoading.generateLoadingFuture(IntegralApi.getTaskIsFinishStatus(TaskType.NoviceTasks)).then((value) {
              if (value == null) return;
              Utils.showBottomSheetDialog(context, shareWidget(int.parse(value)));
            });
            //  弹出 弹窗
          },
          definedGoBack: true,
          // 返回上一页
          goBack: () {
            NativeChannelBridge.instance.closeFlutterPage(num: 1);
          },
          goRank: () {
            Navigator.of(context).push(MaterialPageRoute(
                builder: (_) {
                  return PointsListPage();
                },
                settings: RouteSettings(name: Routes.rankPage)));
          },
        ),
        body: NestedScrollView(
          controller: _scrollController,
          headerSliverBuilder: (c, _) => [
            SliverToBoxAdapter(
              child: integralHeader(),
            ),
          ],
          body: CustomScrollView(
            controller: _scrollController2,
            physics: const NeverScrollableScrollPhysics(),
            slivers: [
              SliverPersistentHeader(
                  pinned: true,
                  delegate: SliverIntegralDelegate(
                      isEmpty: true,
                      tabBar: TabBar(
                        overlayColor: MaterialStateProperty.resolveWith<Color?>(
                          (Set<MaterialState> states) {
                            if (states.contains(MaterialState.hovered)) {
                              // 悬停时的覆盖颜色
                              return Colors.transparent;
                            } else if (states.contains(MaterialState.pressed)) {
                              // 按下时的覆盖颜色
                              return Colors.transparent;
                            }
                            // 默认状态下的覆盖颜色
                            return Colors.transparent; // 或者返回你想要的颜色
                          },
                        ),
                        dividerColor: Color.fromRGBO(224, 224, 224, 1),
                        // tabAlignment: TabAlignment.start,
                        isScrollable: false,
                        labelColor: Color.fromRGBO(5, 1, 1, 1),
                        unselectedLabelColor: Color.fromRGBO(190, 189, 202, 1),
                        indicatorColor: Color.fromRGBO(51, 51, 51, 1),
                        // indicatorWeight: 1,
                        indicator: UnderlineTabIndicator(
                          borderSide: BorderSide(
                            color: Color.fromRGBO(51, 51, 51, 1), // 下划线的颜色
                            width: 1.w, // 下划线的宽度
                          ),
                          insets: EdgeInsets.symmetric(horizontal: 0), // 下划线的水平间距
                        ),
                        indicatorPadding: EdgeInsets.only(left: 0.w, right: 0.w, bottom: 0),
                        tabs: getTabs(),
                        labelPadding: EdgeInsets.only(left: 0.w, right: 0.w),
                        labelStyle: TextStyle(fontWeight: FontWeight.w400, fontSize: 14.sp),
                        controller: _tabController,
                      ),
                      backgroundColor: Colors.transparent)),
              SliverFillRemaining(
                child: tabs[_currentIndex].data.isEmpty
                    ? Container(
                        color: Colors.transparent,
                        child: PageEmptyCom(title: 'Empty data'),
                      )
                    : Container(
                        color: Colors.transparent,
                        height: double.infinity,
                        child: TabBarView(
                            physics: NeverScrollableScrollPhysics(),
                            controller: _tabController,
                            children: tabs.map((element) {
                              return BeginnerTasksPageList(
                                title: element.name,
                                pageStatus: TaskType.NoviceTasks != element.value? isFinish: 1,
                                list: element.data,
                                hasMore: true,
                                onClick: (IntegralTabsItemDataType item) async {
                                  if (item.status == 0 || item.status == 3) {
                                    return true;
                                  }
                                  if (item.status == 1) {
                                    // 原生 处理 的code
                                   if(205 == item.task_code){
                                     if(Platform.isAndroid){
                                       final bool? status = await IntegralApi.isAndroidGroupExist();
                                       if(status==null){
                                         Toast.show(context, message: 'Network anomaly',status: '-1');
                                         return true;
                                       }
                                       if(status==false){
                                         Toast.show(context, message: 'Group does not exist',status: '-1');
                                         return true;
                                       }
                                     }
                                     NativeChannelBridge().toStartPointsTask(num: item.task_code);
                                   }else if([306,307,303,308].contains(item.task_code)){
                                     if([306,307].contains(item.task_code)){
                                       final userId = NativeChannelBridge.instance.appCommMsg?.userId;
                                       final wallet = await ObjectBox().walletModel.getWalletByUId(userId!);
                                       if (wallet == null &&
                                           TaskCodeToFlutter.taskCodeList.contains(item.task_code.toString())) {
                                         Toast.show(context,
                                             message: "The user MPC wallet does not exist, please create a wallet first!",
                                             status: '-1');
                                         return true;
                                       }
                                     }
                                     TaskCodeToFlutter.linkToPage(item.task_code.toString());
                                   }else if ([
                                      202,
                                      203,
                                      204,
                                      301,
                                      302,
                                      304,
                                    ].contains(item.task_code)) {
                                      // 钱包 的跳转没创建 钱包提示
                                      NativeChannelBridge().toStartPointsTask(num: item.task_code,uid: item.task_code==204? custom_uid : null);
                                    } else if ([206, 309].contains(item.task_code)) {
                                      Utils.showBottomSheetDialog(context, shareWidget(item.task_code));
                                    }
                                    else if([310,311].contains(item.task_code)) {
                                      Utils.showBottomSheetDialog(context, shareWidget(309));
                                    }
                                    return true;
                                  }
                                  try {
                                    EasyLoading.generateLoadingFuture(
                                            IntegralApi.postClaimIntegral(taskId: item.task_id))
                                        .then((value) {
                                      if (!value) {
                                        return Toast.show(context, message: "Network abnormality, please make sure the network is normal",status: '-1');
                                      }
                                      // Toast.show(context, message: message)
                                      //   刷新列表数据  刷新当前页面 数据 并且
                                      // 重新 刷新积分
                                      IntegralApi.getUnclaimedScore().then((score) {
                                        totalScore = score == -1 ? totalScore : score;
                                        // 领取积分成功 采取刷新页面
                                        _handleTabSelection();
                                        if (mounted) setState(() {});
                                      });
                                      ClaimSuccessfulDialog.showAboutGas(context);
                                    });
                                    return true;
                                  } catch (e) {
                                    return true;
                                  }
                                  // 前去 领取 奖励
                                },
                              );
                            }).toList(growable: false)),
                      ),
              ),
            ],
          ),
        ),
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Color.fromRGBO(224, 216, 255, 1),
            Color.fromRGBO(237, 244, 255, 1),
            Color.fromRGBO(251, 250, 255, 1),
            Color.fromRGBO(251, 250, 255, 1)
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          stops: [0, 0.30, 0.5, 1.0],
        ),
      ),
    );
  }
}
